package com.wuwei.aliocr.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wuwei.aliocr.domain.*;
import com.wuwei.aliocr.result.Result;
import com.wuwei.aliocr.service.TikuService;
import com.wuwei.aliocr.utils.WxUtils;
import lombok.SneakyThrows;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping(value="/tiku")
@CrossOrigin
public class TikuController {

    @Resource
    private Token token;

    @Resource
    private WxUtils wxUtils;

    @Autowired
    private TikuService tikuService;


    /**
     * 获取用户反馈的题目
     * @return
     * @throws Exception
     */
    @GetMapping("feedback/list/{currentPage}")
    public Result feedback(@PathVariable("currentPage") Integer currentPage) throws Exception {
        System.out.println(currentPage);
        int pageSize = 10;
        int skip = pageSize * (currentPage - 1);
        int limit = pageSize;
        return wxUtils.getSqlFromWxPost("db.collection(\"feedBack\").where({updated:false}).limit("+limit+").skip("+skip+").get()");
    }

    /**
     * 更新feedBack
     * @param updateQuestion
     * @return
     * @throws Exception
     */
    @PostMapping("feedback/update")
    public Result update(@RequestBody UpdateQuestion updateQuestion) throws Exception {
        tikuService.update(updateQuestion);
        return Result.ok(null);
    }

    /**
     * 备份题库
     * @param collection
     * @param resp
     * @return
     * @throws Exception
     */
    @GetMapping("feedback/backup/{collection}")
    public Result backup(@PathVariable("collection") String collection, HttpServletResponse resp) throws Exception {
        String getUrl = tikuService.backupSql(collection);
        System.out.println(getUrl);
        URL url = new URL(getUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(5000);

        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = in.readLine()) != null) {
                response.append(line);
            }
            in.close();
            System.out.println(response.toString());
            String resData = response.toString();
            conn.disconnect();
            return Result.ok(resData);
        } else {
            conn.disconnect();
            return Result.fail(responseCode);
        }
    }

    /**
     * 测试方法，获取token
     * @return
     * @throws Exception
     */
    @GetMapping("token")
    public String getToken() throws Exception {
        String token = wxUtils.testToken();
        return token;
    }

    /**
     * 删除feedBack
     * @param account
     * @param time
     * @return
     */
    @DeleteMapping("feedback/remove/{account}/{time}")
    public Result remove(@PathVariable("account") String account,@PathVariable("time") Long time ){
        System.out.println(account+time);
        tikuService.remove(account,time);
        return Result.ok(null);
    }


    /**
     * 获取题库
     * @return
     * @throws Exception
     */
    @GetMapping("tiku/list")
    public Result tiku () throws Exception {
        return wxUtils.getSqlFromWxPost("db.collection(\"shuati\").get()");
    }

    /**
     * 获取已经修改过的feedBack
     * @param currentPage
     * @return
     * @throws Exception
     */
    @GetMapping("feedback/getRevise/{currentPage}")
    public Result getRevise (@PathVariable("currentPage") Integer currentPage) throws Exception {
        System.out.println(currentPage);
        int pageSize = 10;
        int skip = pageSize * (currentPage - 1);
        int limit = pageSize;
        String query = "db.collection(\"feedBack\").where({\"updated\":true}).skip("+skip+").limit("+limit+").orderBy(\"reviseTime\",\"desc\").get()";
        Result result = wxUtils.getSqlFromWxPost(query);
        return result;
    }

    /**
     * 管理员将原来修订记录里的数据还原的方法
     * @return UpdateForReviseVo
     * @throws Exception
     */
    @PostMapping("feedback/updateForRevise")
    public Result updateForRevise(@RequestBody UpdateForReviseVo updateForReviseVo){
        System.out.println(updateForReviseVo);
        tikuService.UpdateForRevise(updateForReviseVo);
        return Result.ok(null);

    }

    /**
     * 添加题库的方法
     * @param tiKu
     * @return
     */
    @PostMapping("tiku/insert")
    public Result insert(@RequestBody TiKu tiKu){
        System.out.println(tiKu);
        tikuService.insert(tiKu);
        return Result.ok(null);
    }


    /**
     * 得到所有英语听力题目列表
     * @return
     */
    @GetMapping("english/listening/list/{currentPage}")
    public Result listeningList(@PathVariable("currentPage") Integer currentPage){
        Result result = tikuService.listeningList(currentPage);
        return result;
    }

    /**
     * 保存英语听力题目
     * @param englishListening
     * @return
     */
    @PostMapping("english/listening/save")
    public Result saveListening (@RequestBody EnglishListening englishListening){
        System.out.println(englishListening);
        Result result = tikuService.saveListen(englishListening);
        return result;
    }

    /**
     * 随机出题的方法
     * subject:给哪个科目出题
     */
    @GetMapping("tiku/random/{subject}")
    public void random (@PathVariable("subject") String subject, HttpServletResponse response){
        //TODO 后续这里要做成TXT或者WORD格式返回
        JSONArray random = tikuService.random(subject);
        this.printQuestion(random,response);
    }

    /**
     * 获取随机出题的答案方法
     * subject:给哪个科目出题
     */
    @GetMapping("tiku/answer/{subject}")
    public void answer (@PathVariable("subject") String subject, HttpServletResponse response){
        this.printAnswer(response);
    }

    @SneakyThrows
    private void printAnswer(HttpServletResponse response) {
        // 将数据写入到 txt 文件中
        File file = new File("answer.txt");
        BufferedReader reader = new BufferedReader(new FileReader(file));

        // 返回 txt 文件给前端
        try {
            response.setContentType("text/plain");
            PrintWriter out = response.getWriter();
            String str = null;
            while ((str = reader.readLine()) != null) {
                out.println(str);
            }
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将查询到的题目按照好看的格式编写成txt格式传输到前端
     * @param subjectAndRandom
     */
    /**
     * 将查询到的题目按照好看的格式编写成txt格式传输到前端
     */
    private void printQuestion(JSONArray subjectAndRandom, HttpServletResponse response) {
        // 将数据写入到 txt 文件中
        //1 写题目
        this.wirteQuestion(subjectAndRandom,response);
        //2 写答案
        this.wirteAnswer(subjectAndRandom);
        //

    }

    /**
     * 将答案写到浏览器本地
     * @param subjectAndRandom
     */
    private void wirteAnswer(JSONArray subjectAndRandom) {
        File answerFile = new File("answer.txt");
        try (BufferedWriter answerWriter = new BufferedWriter(new FileWriter(answerFile))) {
            for (int i = 0; i < subjectAndRandom.size(); i++) {
                Object s = subjectAndRandom.get(i);
                JSONObject jsonObject = (JSONObject) s;
                String answer = jsonObject.getString("answer");
                answerWriter.write(answer);
                answerWriter.write(System.lineSeparator());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将问题写到浏览器本地
     * @param subjectAndRandom
     * @param response
     */
    private void wirteQuestion(JSONArray subjectAndRandom,HttpServletResponse response) {
        File file = new File("question.txt");
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            for (int i = 0; i < subjectAndRandom.size(); i++) {
                Object s = subjectAndRandom.get(i);
                JSONObject jsonObject = (JSONObject) s;
                String item2 = jsonObject.getString("item2");
                String item1 = jsonObject.getString("item1");
                String item3 = jsonObject.getString("item3");
                String item4 = jsonObject.getString("item4");
                String question = jsonObject.getString("question");
                writer.write(question);
                writer.write(System.lineSeparator());
                writer.write(item1);
                writer.write(System.lineSeparator());
                writer.write(item2);
                writer.write(System.lineSeparator());
                writer.write(item3);
                writer.write(System.lineSeparator());
                writer.write(item4);
                writer.write(System.lineSeparator());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.returnQuestion(response,file);
    }

    /**
     * 返回 txt 文件给前端
     * @param response
     * @param file
     */
    private void returnQuestion(HttpServletResponse response,File file) {
        try {
            response.setContentType("text/plain");
            response.setHeader("Content-Disposition", "attachment;filename=question.txt");
            OutputStream out = response.getOutputStream();
            FileInputStream in = new FileInputStream(file);
            byte[] buffer = new byte[4096];
            int len;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            in.close();
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
